<template>
	<view>
		<view class="background"></view>
		<navView navTitle="文件夹名称" backgroundColor="#008efe" titleColor="#fff" :isBack="true"> </navView>
		<view class="root">
			<view class="list-item" v-for="(item, index) in files" :key="index">
				<image class="file-icon" src="https://hfd.bjlzkj.com/static/list/file.png" />
				<view class="option">
					<view class="file-info">
						<view class="file-title">{{ item.filename }}</view>
						<view class="file-time">{{ item.createtime }}</view>
					</view>
					<view class="file-description">{{ file.filesize }}</view>
					<view class="action-buttons">
						<button class="download-button" @click="handleDownload(item.url)">下载</button>
						<button class="view-button" @click="handleView(item.url)">查看</button>
						<button class="delete-button" @click.stop="confirmDelete(item.id, index)">删除</button>
					</view>
				</view>
			</view>
		</view>
		<image @click="uploadFile" class="addimg" src="https://hfd.bjlzkj.com/static/user/add.png" mode=""></image>

		<!-- 新增公司选择弹窗 -->
		<uni-popup ref="companyPopup" type="bottom" background-color="#fff" class="center-popup">
			<view class="popup-content">
				<view class="search-box">
					<uni-search-bar style="padding:0rpx" placeholder="输入公司名称搜索" v-model="searchKeyword"
						@confirm="searchCompany" cancel-button="none" />
				</view>
				<scroll-view class="company-list" scroll-y="true" @scrolltolower="loadMore">
					<view v-for="(company, index) in companies" :key="index" class="company-item"
						@click="selectCompany(company)">
						{{ company.name }}
					</view>
					<view v-if="hasMore" class="loading-text">加载中...</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import download from '@/util/filesdownload.js'; //
import uniSearchBar from '@/uni_modules/uni-search-bar/components/uni-search-bar/uni-search-bar'
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more'
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup'

export default {
	components: { uniPopup, uniSearchBar, uniLoadMore },
	data() {
		return {
			files: {},
			folderID: null,
			category: "",
			companies: [], // 新增公司列表
			selectedCompanyId: null, // 新增选中的公司ID
			searchKeyword: '',  // 确保已声明
			currentPage: 1,     // 确保已声明
			hasMore: true       // 确保已声明
		}
	},
	onLoad(options) {
		this.folderID = options.id
		this.category = options.category
		this.getFolderFiles()
		this.getCompanyList() // 新增获取公司列表
	},
	onReady() {
		const query = uni.createSelectorQuery().in(this);
		query.select('.modal-content').boundingClientRect(() => {
			// 实现滚动到底部加载更多
		}).exec();
	},
	methods: {
		getFolderFiles() {
			this.$request('/addons/qingdong/folder/getFolderFiles', 'GET', {
				folder_id: this.folderID
			}).then(res => {
				const formattedData = res.data.map(item => ({
					...item,
					createtime: this.formatTime(item.createtime),
					filesize: this.formatFileSize(item.filesize)
				}));
				this.files = formattedData
			})
		},
		// 新增删除确认方法
		confirmDelete(fileId, index) {
			uni.showModal({
				title: '删除确认',
				content: '确定要删除这个文件吗？',
				success: (res) => {
					if (res.confirm) {
						this.deleteFile(fileId)
						this.files.splice(index, 1) // 立即更新视图
					}
				}
			})
		},
		deleteFile(fileID) {
			this.$request('/addons/qingdong/folder/deleteFile', 'POST', {
				file_id: fileID
			}).then(res => {
				if (res.code === 1) {
					this.getFolderFiles()
				}
			})
		},
		// 新增时间格式化方法
		formatTime(timestamp) {
			const date = new Date(timestamp * 1000);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} 
            ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
		},
		// 新增文件大小格式化
		formatFileSize(bytes) {
			if (bytes === 0) return '0 B';
			const k = 1024;
			const sizes = ['B', 'KB', 'MB', 'GB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));
			return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
		},
		// 下载文件
		handleDownload(url) {
			download.downloadFun(url);
		},
		handleView(url) {
			// 检查文件是否已下载
			uni.showLoading({ title: '正在打开...' });  // 新增加载提示
			uni.downloadFile({
				url: url,
				success: function (res) {
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: encodeURI(filePath),
						showMenu: true,
						success: function (res) {
							uni.hideLoading();  // 隐藏加载提示
							console.log('打开文档成功', res);
						},
						fail: function (err) {
							uni.hideLoading();  // 隐藏加载提示
							console.error('打开文档失败', err);
						}
					});
				},
				fail: (err) => {
					uni.hideLoading();  // 隐藏加载提示
					console.error('下载失败', err);
					uni.showToast({ title: '文件下载失败', icon: 'none' });  // 新增失败提示
				}
			});
		},
		// 去上传按钮点击事件
		async uploadFile() {
			// 先显示公司选择弹窗
			this.$refs.companyPopup.open();
		},

		// 公司选择方法
		selectCompany(company) {
			this.selectedCompanyId = company.id;
			this.$refs.companyPopup.close();
			this.startUploadProcess();
		},

		// 启动上传流程
		async startUploadProcess() {
			const token = uni.getStorageSync('user_token');
			uni.chooseImage({
				count: 9,
				type: 'all',
				success: async (res) => {
					const result = uni.uploadFile({
						url: 'https://hfd.bjlzkj.com/addons/qingdong/common/companyupload',
						filePath: res.tempFilePaths[0],  // 改用tempFilePaths数组中的路径
						name: 'file',  // 后端接收文件的参数名
						formData: {
							category: this.category,  // 添加分类参数
							folder_id: this.folderID,
							customer_id: this.selectedCompanyId,  // 添加公司ID参数
						},
						header: {
							'Content-Type': 'application/json',
							'token': token // 新增token请求头
						},
						success: (uploadFileRes) => {
							console.log('上传结果:', uploadFileRes);
							uni.showToast({ title: '上传成功' });
							this.currentPage = 1;
							this.fileList = [];
							this.getFolderFiles();
						},
						fail: (err) => {
							console.error('上传失败:', err);
							uni.showToast({ title: '上传失败', icon: 'none' });
						},
					})
				}
			});
		},

		// 搜索公司
		searchCompany() {
			this.currentPage = 1;
			this.getCompanyList(this.searchKeyword);
		},

		// 加载更多
		loadMore() {
			if (this.hasMore) {
				this.currentPage++;
				this.getCompanyList(this.searchKeyword, this.currentPage);
			}
		},

		// 修改后的获取公司列表方法
		async getCompanyList(keyword = '', page = 1) {
			await this.$request('/addons/qingdong/customer/getSearchCustomerList', 'GET', {
				page,
				keyword
			}).then(res => {
				const newData = res.data.data;
				this.companies = page === 1 ? newData : [...this.companies, ...newData];
				this.hasMore = res.data.current_page < res.data.last_page;
			});
		}
	}
}
</script>

<style lang="less">
.background {
	background: #f5f6f9;
	width: 100%;
	height: 100vh;
	position: fixed;
	top: 0;
	left: 0;
	z-index: -1;
}

.root {
	padding: 20rpx;
	box-sizing: border-box;

	.list-item {
		display: flex;
		align-items: center;
		position: relative;
		justify-content: space-between;
		background: #fff;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
		box-sizing: border-box;

		&:last-child {
			border: 0;
		}

		.file-icon {
			width: 60px;
			height: 60px;
		}

		.option {
			width: 80%;

			.file-info {
				flex: 1;

				.file-title {
					font-size: 9.5px;
					font-weight: bold;
					color: #333;
				}

				.file-time {
					font-size: 10px;
					color: #999;
					margin-top: 4px;
				}
			}

			.action-buttons {
				width: 100%;
				display: flex;
				justify-content: flex-end;
				margin-top: 20rpx;

				.download-button {
					width: 150rpx;
					height: 50rpx;
					border-radius: 58rpx 58rpx 58rpx 58rpx;
					border: 4rpx solid #008EFF;
					font-size: 20rpx;
					color: #008EFF;
					background: #fff;
					margin: 0;
				}

				.view-button {
					width: 150rpx;
					height: 50rpx;
					border-radius: 58rpx 58rpx 58rpx 58rpx;
					border: 4rpx solid #008EFF;
					font-size: 20rpx;
					color: #fff;
					background: #008EFF;
					margin: 0;
					margin-left: 20rpx;
				}

				.delete-button {
					width: 150rpx;
					height: 50rpx;
					border-radius: 58rpx;
					background: linear-gradient(45deg, #ff5a5a, #ff3a3a);
					font-size: 20rpx;
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					margin: 0;
					transition: all 0.3s;
					margin-left: 18rpx;

					&:active {
						opacity: 0.8;
						transform: scale(0.95);
					}
				}
			}
		}
	}
}

.addimg {
	width: 96rpx;
	height: 96rpx;
	position: fixed;
	bottom: 120rpx;
	right: 40rpx;
}

.center-popup {
	display: flex;
	align-items: flex-start;
	justify-content: center;
}

.popup-content {
	width: 100%;
	max-width: 600rpx; // 增加最大宽度限制
	min-width: 500rpx; // 新增最小宽度限制
	height: 60vh;
	border-radius: 24rpx; // 增加圆角
	box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.1); // 增强阴影效果
	margin-top: 40rpx;

	.popup-header {
		padding: 30rpx 0;
		font-weight: bold;
		font-size: 32rpx;
		color: #333;
		border-bottom: 1rpx solid #eee;
	}

	.search-box {
		margin: 30rpx 0; // 恢复合理边距
		padding: 0 30rpx;
		background: #f5f5f5;

		::v-deep .uni-searchbar {
			padding: 20rpx 0 !important; // 增加搜索框垂直间距
		}
	}

	.company-list {
		height: calc(100% - 160rpx);
		display: flex;
		flex-direction: column;

		.company-item {
			padding: 28rpx 30rpx; // 增加左右内边距
			font-size: 30rpx; // 增大字号
			color: #333;
			border-bottom: 1rpx solid #f5f5f5;
			transition: all 0.2s;
			text-align: center;

			&:active {
				background-color: #fafafa;
			}

			&:last-child {
				border-bottom: none;
			}
		}

		.loading-text {
			padding: 30rpx;
			color: #999;
			display: flex;
			align-items: center;
			justify-content: center;

			&::after {
				content: "";
				display: inline-block;
				width: 24rpx;
				height: 24rpx;
				border: 4rpx solid #ddd;
				border-top-color: #008EFF;
				border-radius: 50%;
				margin-left: 10rpx;
				animation: spin 0.8s linear infinite;
			}
		}
	}
}

@keyframes spin {
	to {
		transform: rotate(360deg);
	}
}
</style>